from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from .models import Roles, Menus


class RoleSerializers(ModelSerializer):
    menu_ids = serializers.ListField(child=serializers.IntegerField(), write_only=True)
    created_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    updated_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)

    class Meta:
        model = Roles
        fields = ["id", "name", "is_show", "orders", "menu_ids", "description", "created_at", "updated_at"]
        read_only_fields = ["id", "created_at", "updated_at"]
        extra_kwargs = {
            "orders": {"required": False},
            "description": {"required": False},
            "is_show": {"required": False}
        }

    def validate(self, attrs):
        return attrs

    def validate_menu_ids(self, item):
        for menu_id in item:
            menu = Menus.objects.filter(id=menu_id).first()
            if not menu:
                raise ValidationError(f"菜单id:{menu_id}不存在")
        return item
